//
//  WaterfallLayout.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import SwiftUI

struct WaterfallLayout: View {
    let notes: [CommunityNote]
    let onLoadMore: () async -> Void
    
    private let columns = 2
    private let spacing: CGFloat = 8
    
    var body: some View {
        LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: spacing), count: columns), spacing: spacing) {
            ForEach(notes) { note in
                NoteCardView(note: note)
                    .onAppear {
                        // 当显示到倒数第5个item时，触发加载更多
                        if note.id == notes.suffix(5).first?.id {
                            Task {
                                await onLoadMore()
                            }
                        }
                    }
            }
        }
    }
}

// MARK: - 笔记卡片视图
struct NoteCardView: View {
    let note: CommunityNote
    @State private var isLiked = false
    @State private var likeCount = 0
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            // 笔记图片
            AsyncImage(url: URL(string: note.images.first ?? "")) { image in
                image
                    .resizable()
                    .aspectRatio(contentMode: .fill)
            } placeholder: {
                Rectangle()
                    .fill(Color.gray.opacity(0.3))
                    .aspectRatio(0.75, contentMode: .fit)
            }
            .clipped()
            .cornerRadius(8)
            
            // 笔记标题
            Text(note.title)
                .font(.system(size: 14, weight: .medium))
                .lineLimit(2)
                .foregroundColor(.primary)
            
            // 作者信息和互动
            HStack(spacing: 8) {
                // 作者头像
                AsyncImage(url: URL(string: note.authorAvatar)) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                } placeholder: {
                    Circle()
                        .fill(Color.gray.opacity(0.3))
                }
                .frame(width: 20, height: 20)
                .clipShape(Circle())
                
                // 作者昵称
                Text(note.authorName)
                    .font(.caption)
                    .foregroundColor(.gray)
                    .lineLimit(1)
                
                Spacer()
                
                // 点赞按钮
                Button(action: {
                    Task {
                        await likeNote()
                    }
                }) {
                    HStack(spacing: 4) {
                        Image(systemName: isLiked ? "heart.fill" : "heart")
                            .font(.caption)
                            .foregroundColor(isLiked ? .red : .gray)
                        
                        Text("\(likeCount)")
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                }
            }
        }
        .padding(8)
        .background(Color.white)
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.05), radius: 2, x: 0, y: 1)
        .onAppear {
            isLiked = note.userIsLike
            likeCount = note.likeNum
        }
    }
    
    private func likeNote() async {
        let originalLiked = isLiked
        let originalCount = likeCount
        
        // 乐观更新UI
        isLiked.toggle()
        likeCount += isLiked ? 1 : -1
        
        // 调用API
        do {
            let response: APIResponse<Bool> = try await APIService.shared.likeNote(noteId: note.id)
            if response.status != 200 {
                // 如果失败，恢复原状态
                isLiked = originalLiked
                likeCount = originalCount
            }
        } catch {
            // 如果失败，恢复原状态
            isLiked = originalLiked
            likeCount = originalCount
            print("点赞失败: \(error)")
        }
    }
}

// MARK: - 瀑布流网格布局（自定义实现）
struct StaggeredGrid<Content: View>: View {
    let columns: Int
    let spacing: CGFloat
    let content: () -> Content
    
    init(columns: Int, spacing: CGFloat = 8, @ViewBuilder content: @escaping () -> Content) {
        self.columns = columns
        self.spacing = spacing
        self.content = content
    }
    
    var body: some View {
        GeometryReader { geometry in
            let columnWidth = (geometry.size.width - CGFloat(columns - 1) * spacing) / CGFloat(columns)
            
            HStack(alignment: .top, spacing: spacing) {
                ForEach(0..<columns, id: \.self) { columnIndex in
                    LazyVStack(spacing: spacing) {
                        content()
                    }
                    .frame(width: columnWidth)
                }
            }
        }
    }
}

struct WaterfallLayout_Previews: PreviewProvider {
    static var previews: some View {
        ScrollView {
            WaterfallLayout(notes: []) { }
                .padding()
        }
    }
}